package com.ruoyi.classai.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.classai.domain.*;
import com.ruoyi.classai.domain.dto.EwcStudentDto;
import com.ruoyi.classai.domain.dto.GroupDto;
import com.ruoyi.classai.domain.dto.GroupListDto;
import com.ruoyi.classai.domain.dto.ModuleLessonPreparationModificationDto;
import com.ruoyi.classai.domain.vo.CommentModuleVo;
import com.ruoyi.classai.domain.vo.CourseGroupingRank;
import com.ruoyi.classai.domain.vo.GroupVo;
import com.ruoyi.classai.mapper.EwcCourseGroupingMapper;
import com.ruoyi.classai.service.IEwcAttendanceRecordsService;
import com.ruoyi.classai.service.IEwcCourseGroupingService;
import com.ruoyi.classai.service.IEwcGroupingStrategyCodeService;
import com.ruoyi.classai.service.IEwcStudentService;
import com.ruoyi.classai.utils.group.GroupUtils;
import com.ruoyi.classai.utils.group.Student;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
/**
 * 课程分组Service业务层处理
 * 
 * @author lcj
 * @date 2025-02-28
 */
@Slf4j
@Service
public class EwcCourseGroupingServiceImpl extends ServiceImpl<EwcCourseGroupingMapper, EwcCourseGrouping> implements IEwcCourseGroupingService {

    @Autowired
    private IEwcGroupingStrategyCodeService groupingStrategyCodeService;
    @Autowired
    private IEwcStudentService studentService;
    @Autowired
    private EwcCourseGroupingMapper courseGroupingMapper;
    @Autowired
    private IEwcAttendanceRecordsService attendanceRecordsService;
    @Override
    public boolean updateCourseGroupingFile(EwcCourseGrouping ewcCourseGrouping) {
        // 创建 UpdateWrapper 对象
        UpdateWrapper<EwcCourseGrouping> updateWrapper = new UpdateWrapper<>();
        // 设置更新条件
        updateWrapper.eq("grouping_id", ewcCourseGrouping.getGroupingId())
                .eq("student_id", ewcCourseGrouping.getStudentId())
                .eq("class_id", ewcCourseGrouping.getClassId())
                .eq("course_id", ewcCourseGrouping.getCourseId())
                .eq("chapter_id", ewcCourseGrouping.getChapterId())
                .eq("course_id", ewcCourseGrouping.getCourseId());

        // 设置要更新的字段及其值
        EwcCourseGrouping updateEntity = new EwcCourseGrouping();
        updateEntity.setVideoPath(ewcCourseGrouping.getVideoPath());

        // 执行更新操作
        return this.update(updateEntity, updateWrapper);
    }

    @Override
    public void addGroup(GroupDto groupDto) {
        //查询分组策略
        EwcGroupingStrategyCode groupingStrategyCode =groupingStrategyCodeService.getById(groupDto.getStrategyId());
        //查询班级学生信息
        List<EwcStudentDto> students=studentService.getList(null, groupDto.getClassId());
        if(CollectionUtil.isEmpty(students)){
            throw new GlobalException("没有查询到学生信息");
        }
        List<Student> groupStudent=new ArrayList<>();
        for (EwcStudentDto s : students) {
            //查询学生是否签到
            EwcAttendanceRecords attendanceRecords=attendanceRecordsService.getOne(Wrappers.<EwcAttendanceRecords>lambdaQuery().eq(EwcAttendanceRecords::getStudentId,s.getId())
                    .eq(EwcAttendanceRecords::getClassId,groupDto.getClassId())
                    .eq(EwcAttendanceRecords::getCourseId,groupDto.getCourseId())
                    .eq(EwcAttendanceRecords::getChapterId,groupDto.getChapterId())
                    .eq(EwcAttendanceRecords::getAttendanceStatus,Constants.COMMON_SUCCESS)); //已签到
            if (Objects.nonNull(attendanceRecords)) { //考勤不为空
                groupStudent.add(new Student(s.getId(), s.getStudentName(), s.getGender(), 0L,s.getGroupId()));
            }
        }
        if(CollectionUtil.isEmpty(groupStudent)){
            throw new GlobalException("没有查询到考勤学生信息");
        }
        //分配列表
        List<List<Student>> fpList;
        if ("GS001".equals(groupingStrategyCode.getStrategyCode())){  //随机分组
            fpList = GroupUtils.randomGroup(groupStudent,groupDto.getGroupSize());
        } else if ("GS002".equals(groupingStrategyCode.getStrategyCode())) { //男女分组
            fpList =GroupUtils.sexRandomGroup(groupStudent,groupDto.getGroupSize());
        }else if ("GS000".equals(groupingStrategyCode.getStrategyCode())){//默认分组
            fpList =GroupUtils.defaultRandomGroup(groupStudent);
        }else {
            throw new GlobalException("未知分组信息");
        }
        int i=1;
        //查询最新的moduleCode
        EwcCourseGrouping newCourseGrouping=this.getOne(Wrappers.<EwcCourseGrouping>lambdaQuery()
                .eq(EwcCourseGrouping::getChapterId,groupDto.getChapterId())
                .orderByDesc(EwcCourseGrouping::getGroupNumber).last("limit 1"));
        Integer groupNumber=Objects.nonNull(newCourseGrouping)&&Objects.nonNull(newCourseGrouping.getGroupNumber())?
               newCourseGrouping.getGroupNumber()+1:1;
        //添加到课程分组表
        for (List<Student> studentList : fpList) {
            String gourpId=IdUtil.fastSimpleUUID();
            for (Student student : studentList) {
                //添加分组信息
                EwcCourseGrouping courseGrouping=new EwcCourseGrouping();
                courseGrouping.setGroupingId(gourpId);
                courseGrouping.setGroupingName("第"+i+"组");
                courseGrouping.setModuleCode(String.valueOf(groupDto.getStrategyId()));
                //分组次数
                courseGrouping.setGroupNumber(groupNumber);
                courseGrouping.setStudentId(student.getId());
                courseGrouping.setClassId(groupDto.getClassId());
                courseGrouping.setCourseId(groupDto.getCourseId());
                courseGrouping.setChapterId(groupDto.getChapterId());
                courseGrouping.setSort(i);
                this.save(courseGrouping);
            }
            i++;
        }
    }

    @Override
    public JSONObject getGroupList(GroupListDto groupDto) {
        //查询最新的moduleCode
        EwcCourseGrouping newCourseGrouping=this.getOne(Wrappers.<EwcCourseGrouping>lambdaQuery()
                .eq(EwcCourseGrouping::getChapterId,groupDto.getChapterId())
                .orderByDesc(EwcCourseGrouping::getGroupNumber).last("limit 1"));
        if (Objects.isNull(newCourseGrouping)){
            log.info("没有查询到分组信息");
            return null;
        }
        List<EwcCourseGrouping> courseGroupings=this.list(Wrappers.<EwcCourseGrouping>lambdaQuery()
                .eq(EwcCourseGrouping::getGroupNumber,newCourseGrouping.getGroupNumber())
                .eq(EwcCourseGrouping::getChapterId,groupDto.getChapterId())
                .select(EwcCourseGrouping::getSort)
                .orderByAsc(EwcCourseGrouping::getSort)
                .groupBy(EwcCourseGrouping::getSort));

        JSONObject json=new JSONObject();
        List<List<GroupVo>> list=new ArrayList<>();
        for (EwcCourseGrouping courseGrouping : courseGroupings) {
            List<EwcCourseGrouping> groupings=this.list(Wrappers.<EwcCourseGrouping>lambdaQuery()
                    .eq(EwcCourseGrouping::getGroupNumber,newCourseGrouping.getGroupNumber())
                    .eq(EwcCourseGrouping::getChapterId,groupDto.getChapterId())
                    .eq(EwcCourseGrouping::getSort,courseGrouping.getSort()));
            List<GroupVo> students=new ArrayList<>();
            for (EwcCourseGrouping grouping : groupings) {
                EwcStudent ewcStudent=studentService.getById(grouping.getStudentId());
                if (Objects.nonNull(ewcStudent)){
                    GroupVo groupVo=new GroupVo();
                    groupVo.setGroupingName(grouping.getGroupingName());
                    groupVo.setModuleCode(grouping.getModuleCode());
                    groupVo.setGroupNumber(newCourseGrouping.getGroupNumber());
                    groupVo.setStudentId(ewcStudent.getId());
                    groupVo.setStudentName(ewcStudent.getStudentName());
                    groupVo.setGroupingId(grouping.getGroupingId());
                    groupVo.setGender(ewcStudent.getGender());
                    groupVo.setAvatarPath(ewcStudent.getAvatarPath());
                    groupVo.setSort(grouping.getSort());
                    students.add(groupVo);
                }
            }
            list.add(students);
        }
        json.put("size",list.size());
        json.put("strategyId",newCourseGrouping.getModuleCode());
        json.put("groupData",list);
        return json;
    }

    @Override
    public void getGroupAdjust(String groupingId, String moveGroupingId,String studentId,Integer sort,String groupingName) {
        //查询分组信息
        EwcCourseGrouping courseGrouping=this.getOne(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getGroupingId,groupingId)
                .eq(EwcCourseGrouping::getStudentId,studentId).last("limit 1"));
        EwcCourseGrouping moveCourseGrouping=this.getOne(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getGroupingId,moveGroupingId).last("limit 1"));
        //判断移动分组是否存在
        if (Objects.nonNull(moveCourseGrouping)) {
            courseGrouping.setGroupingName(moveCourseGrouping.getGroupingName());
            courseGrouping.setGroupingId(moveCourseGrouping.getGroupingId());
            courseGrouping.setSort(moveCourseGrouping.getSort());
            this.save(courseGrouping);
        }else {
            courseGrouping.setGroupingName(groupingName);
            courseGrouping.setGroupingId(IdUtil.fastSimpleUUID());
            courseGrouping.setSort(sort);
            this.save(courseGrouping);
        }
        //删除原来分组
        this.remove(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getGroupingId,groupingId)
                .eq(EwcCourseGrouping::getStudentId,studentId));
    }

    @Override
    public CommentModuleVo queryCommentModuleDate(ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto) {
        //查询最新的moduleCode
//        EwcCourseGrouping newCourseGrouping=this.getOne(Wrappers.<EwcCourseGrouping>lambdaQuery()
//                .eq(EwcCourseGrouping::getChapterId,moduleLessonPreparationModificationDto.getChapterUniqueId())
//                .orderByDesc(EwcCourseGrouping::getGroupNumber).last("limit 1"));
//        if (Objects.isNull(newCourseGrouping)){
//            throw new GlobalException("没有查询到分组信息");
//        }
        //获取最大分组信息   module_code最大的
        //int maxGroup=courseGroupingMapper.querMaxGrouping(moduleLessonPreparationModificationDto);
        //moduleLessonPreparationModificationDto.setModuleCode(String.valueOf(maxGroup));

        // 创建 UpdateWrapper 对象
        QueryWrapper<EwcCourseGrouping> queryWrapper = new QueryWrapper<>();
        // 设置更新条件
        queryWrapper.eq("class_id", moduleLessonPreparationModificationDto.getClassId())
                .eq("course_id", moduleLessonPreparationModificationDto.getCourseId())
                .eq("group_number", moduleLessonPreparationModificationDto.getGroupNumber())
                .eq("chapter_id", moduleLessonPreparationModificationDto.getChapterUniqueId());
        //学生人数，小组数量，上传进度，平均成绩
        String classId = moduleLessonPreparationModificationDto.getClassId();
        String courseId = moduleLessonPreparationModificationDto.getCourseId();
        Integer groupNumber = moduleLessonPreparationModificationDto.getGroupNumber();
        String chapterUniqueId = moduleLessonPreparationModificationDto.getChapterUniqueId();
        int totalStudents = Math.toIntExact(courseGroupingMapper.selectCount(queryWrapper));//学生人数
        Map<String, Object> params = new HashMap<>();
        params.put("classId", classId);
        params.put("courseId", courseId);
        params.put("groupNumber", groupNumber);
        params.put("chapterId", chapterUniqueId);
        //查询分组数量
        Long totalGroup =  courseGroupingMapper.selectDistinctClassIdCount(params);
        QueryWrapper<EwcCourseGrouping> queryWrapperUpload = new QueryWrapper<>();
        // 设置更新条件
        queryWrapperUpload.eq("class_id", moduleLessonPreparationModificationDto.getClassId())
                .eq("course_id", moduleLessonPreparationModificationDto.getCourseId())
                .eq("group_number", moduleLessonPreparationModificationDto.getGroupNumber())
                .isNotNull("video_path")
                .eq("chapter_id", moduleLessonPreparationModificationDto.getChapterUniqueId());
        int uploadCount = Math.toIntExact(courseGroupingMapper.selectCount(queryWrapperUpload));//学生人数
        int uploadProgress = 0;
        if (totalStudents > 0) {
            log.debug("uploadCount:" + uploadCount);
            log.debug("uploadProgress:" + uploadProgress);
            uploadProgress = uploadCount*100 / totalStudents;
            log.debug("uploadProgress:" + uploadProgress);
        }
        QueryWrapper<EwcCourseGrouping> queryWrapperAvg = new QueryWrapper<>();
        // 设置更新条件
        queryWrapperAvg.eq("class_id", moduleLessonPreparationModificationDto.getClassId())
                .eq("course_id", moduleLessonPreparationModificationDto.getCourseId())
                .eq("group_number", moduleLessonPreparationModificationDto.getGroupNumber())
                .eq("chapter_id", moduleLessonPreparationModificationDto.getChapterUniqueId());

        Long avgScore = courseGroupingMapper.getAvg(params);//学生人数
        moduleLessonPreparationModificationDto.setGroupNumber(moduleLessonPreparationModificationDto.getGroupNumber());
        List<CourseGroupingRank> courseGroupingRankList=courseGroupingMapper.getCourseGroupingRank(moduleLessonPreparationModificationDto);
//        // 创建 QueryWrapper 对象
//        QueryWrapper<EwcCourseGrouping> queryWrapperCourseGrouping = new QueryWrapper<>();
//        // 设置查询条件
//        queryWrapperCourseGrouping.eq("class_id", moduleLessonPreparationModificationDto.getClassId())
//                .eq("course_id", moduleLessonPreparationModificationDto.getCourseId())
//                .eq("module_code", moduleLessonPreparationModificationDto.getModuleCode())
//                .eq("chapter_id", moduleLessonPreparationModificationDto.getChapterUniqueId());
//
//        List<EwcCourseGrouping> list = this.list(queryWrapperCourseGrouping);
       //获取小组排名

        CommentModuleVo commentModuleVo=new CommentModuleVo();
        commentModuleVo.setEwcCourseGrouping(courseGroupingRankList);
        commentModuleVo.setUploadProgress(String.valueOf(uploadProgress));
        commentModuleVo.setAvgScore(String.valueOf(avgScore));
        commentModuleVo.setTotalGroup(String.valueOf(totalGroup));
        commentModuleVo.setTotalStudents(String.valueOf(totalStudents));
        return commentModuleVo;
    }

    @Override
    public void updateByFileName(AnalysisModeRel analysisModeRel,String aiResult) {
        UpdateWrapper<EwcCourseGrouping> queryWrapper = Wrappers.update();
        queryWrapper.eq("task_id", analysisModeRel.getTask_id());
        EwcCourseGrouping ewcCourseGrouping= new EwcCourseGrouping();
        ewcCourseGrouping.setAnalysisVideoPath(analysisModeRel.getFilePath());
        String scoreStr = analysisModeRel.getScore();
        BigDecimal score = scoreStr == null||scoreStr.equals("") ? BigDecimal.ZERO : new BigDecimal(scoreStr);
        ewcCourseGrouping.setScore(score);
        ewcCourseGrouping.setScoreDescription(analysisModeRel.getAnalysis_msg());
        ewcCourseGrouping.setAimodelDescriotion(aiResult);

        ewcCourseGrouping.setSynthesisSpeed(new BigDecimal(analysisModeRel.getSynthesisSpeed()));
        ewcCourseGrouping.setSynthesisGesture(new BigDecimal(analysisModeRel.getSynthesisGesture()));
        ewcCourseGrouping.setSynthesisRhythm(new BigDecimal(analysisModeRel.getSynthesisRhythm()));
        ewcCourseGrouping.setType(analysisModeRel.getType());
        this.update(ewcCourseGrouping,queryWrapper);
    }

    @Override
    public List<GroupStudentDetail> queryGroupDetail(ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto) {
        List<GroupStudentDetail> groupDetailVoList= courseGroupingMapper.queryGroupDetail(moduleLessonPreparationModificationDto);
        return groupDetailVoList;
    }

    @Override
    public EwcCourseGrouping getGroupName(String groupingId) {
        QueryWrapper<EwcCourseGrouping>  queryWrapper = Wrappers.query();
        queryWrapper.eq("grouping_id",groupingId);
        queryWrapper.select("grouping_id, grouping_name,ROUND(AVG(score), 2) as score ");
        List<String> columns = new ArrayList<>();
        columns.add("grouping_id");
        columns.add("grouping_name");
        queryWrapper.groupBy(columns);
        return this.getOne(queryWrapper);
    }

    @Override
    public QueryAiMsg queryAiMsg(AnalysisModeRel analysisModeRel) {
        return courseGroupingMapper.queryAiMsgg(analysisModeRel);
    }

    @Override
    public List<Integer> getGroupNum(String chapterId) {

        return courseGroupingMapper.getGroupNum(chapterId);
    }

    @Override
    public void updateByFileNameForFai(AnalysisModeRel analysisModeRel) {
        UpdateWrapper<EwcCourseGrouping> queryWrapper = Wrappers.update();
        queryWrapper.eq("task_id", analysisModeRel.getTask_id());
        EwcCourseGrouping ewcCourseGrouping= new EwcCourseGrouping();
        ewcCourseGrouping.setScoreDescription(analysisModeRel.getAnalysis_msg());
        this.update(ewcCourseGrouping,queryWrapper);
    }


}
